package jsystem.gdrive;

import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class DriveCommandLine {

    private static String CLIENT_ID = "360029598627.apps.googleusercontent.com";
    private static String CLIENT_SECRET = "NlYX4YpnT_PxKHk8YPYSCbXH";
    private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    public static void main(String[] args) throws Exception {

        java.io.File certFile = new java.io.File("D:\\jssecacerts");
        System.out.println("Loading KeyStore " + certFile + "...");
        InputStream in = new FileInputStream(certFile);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(in, "Password01_".toCharArray());
        in.close();
        /* Load the keyStore that includes self-signed cert as a "trusted" entry. */
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();

        HttpTransport httpTransport = new NetHttpTransport.Builder().setSslSocketFactory(sslSocketFactory).build();
//        HttpTransport httpTransport = new NetHttpTransport();

        JsonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential();

        CredentialStore credentialStore = new FileCredentialStore(new java.io.File("D://FileCredentialStore.txt"), jsonFactory);
        if (credentialStore.load("buczkotamas@gmail.com", credential)) {
            System.out.println("Credential.getExpiresInSeconds = " + credential.getExpiresInSeconds());
            if (credential.getExpiresInSeconds() < 1) {
                credential.refreshToken();
                credentialStore.store("buczkotamas@gmail.com", credential);
            }
        } else {
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                    httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
                    .setAccessType("online").setApprovalPrompt("auto").build();
            String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
            System.out.println("Please open the following URL in your browser then type the authorization code:");
            System.out.println("  " + url);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String code = br.readLine();
            GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
            credential = new GoogleCredential().setFromTokenResponse(response);
            credentialStore.store("buczkotamas@gmail.com", credential);
        }
        
        //Create a new authorized API client
        Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential).build();

        Files.List request = drive.files().list();
        FileList files = request.execute();
        for (File file : files.getItems()) {
            System.out.println("OriginalFilename = " + file.getOriginalFilename());
            System.out.println("Title = " + file.getTitle());
            System.out.println("IconLink = " + file.getIconLink());
            System.out.println("MimeType = " + file.getMimeType());
        }

        //Insert a file  
//        File body = new File();
//        body.setTitle("My document");
//        body.setDescription("A test document");
//        body.setMimeType("text/plain");
//        java.io.File fileContent = new java.io.File("D://FileCredentialStore.txt");
//        FileContent mediaContent = new FileContent("text/plain", fileContent);
//        File file = drive.files().insert(body, mediaContent).execute();
//        System.out.println("File ID: " + file.getId());
    }
}